﻿using System.Text;

namespace TPXSDK.NET.Mission.Instruction;

internal class InstLand : Tokenizer
{
    public InstLand(TokenizerAdmin admin)
    {
        Admin = admin;
        KeyName = "land";
        KeyValue = (byte)FlyCmdId.CMD_LAND;
        Usage = "land [(landpoint)] [,alt]";
        Description = @"Return to land point and do land";
    }

    /// <inheritdoc />
    /// <summary>
    /// 词元分析器处理过程
    /// </summary>
    public override bool Process()
    {
        var flyCmp = Admin?.Compiler; if (null == flyCmp) return false;
        var tokens = flyCmp.GetLineTokens();
        // 无效参数过滤
        if (null == tokens || tokens.Count > 3)
        {
            flyCmp.ErrorMsg = $"{KeyName} Invalid Usage";
            return false;
        }

        var result = false;
        var cmd = new FlyCmdItem
        {
            Id = (byte)KeyValue,
            LineNum = tokens[0].Row
        };

        if (1 == tokens.Count)
        {
            cmd.P1 = (byte)ParaType.EMPTY;
            cmd.P2 = 0;
            result = true;
        }
        else
        {
            tokens.RemoveAt(0);// Remove Flycmd Name
            if (tokens[0].Type == TokenType.ABS_POS || tokens[0].Type == TokenType.REL_POS)
            {
                result = FlyUtils.WpToken2CmdItemP1(tokens[0], cmd);
            }
        }

        if (result)
        {
            if (tokens.Count == 2 && tokens[1].Type == TokenType.NUMBER)
            {
                cmd.P2 = FlyUtils.ToInt16(tokens[1].Name);
            }

            flyCmp.CmdList.Add(cmd);
        }

        return result;
    }

    public override void Reverse(FlyCmdItem cmd, StringBuilder sb)
    {
        var src = $"{KeyName} {FlyUtils.ParseWpFromCmdItem(cmd)}";
        if (cmd.P1 == 0)
            src = $"{KeyName}";
        if (cmd.P2 != 0)
            src = $"{KeyName} {FlyUtils.ParseWpFromCmdItem(cmd)}, {cmd.P2}";
        sb.AppendLine(src);
    }
}
